package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private static DataSource dataSource = null;

    static {
        //1.创建properties对象
        Properties p = new Properties();
        //2.获取配置文件的 字节输入流
        InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
        //3.加载配置文件
        try {
            p.load(in);
            //4.通过druidfactory获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //0.提供一个方法获取连接对象
    public static DataSource getDs() {
        return dataSource;
    }

    //1.提供一个方法获取连接对象
    public static Connection getCon() {
        Connection con = null;
        try {
            con = dataSource.getConnection();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    //2.释放资源的方法
    public static void closeRes(Connection con, Statement sta, ResultSet rs){

        try {
            if (con != null) {
                con.close();
            }
            if (sta != null) {
                sta.close();
            }
            if (rs != null) {
                rs.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        }
    }
